package com.stevenmoon.csdnplus.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.orhanobut.logger.Logger;
import com.stevenmoon.csdnplus.R;
import com.stevenmoon.csdnplus.activity.MainActivity;
import com.stevenmoon.csdnplus.app.AppService;
import com.stevenmoon.csdnplus.bean.headline.HeadlineColumnBean;
import com.stevenmoon.csdnplus.event.HeadlineTabReselectedEvent;
import com.stevenmoon.csdnplus.fragment.base.BaseFragment;
import com.stevenmoon.csdnplus.fragment.base.ToolbarBaseFragment;
import com.stevenmoon.csdnplus.presenter.HeadlineMainPresenter;
import com.stevenmoon.csdnplus.util.TipUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

/**
 * Created by WangJun on 2016/4/10.
 */
public class HeadlineMainFragment extends ToolbarBaseFragment<HeadlineMainFragment, HeadlineMainPresenter> {

    @Bind(R.id.viewPager)
    ViewPager mViewPager;
    @Bind(R.id.tabLayout)
    TabLayout mTabLayout;
    @Bind(R.id.loadingView)
    View mLoadingView;

    HeadlinePagerAdapter mPagerAdapter;

    private Map<Integer, Fragment> mFragmentMap = new HashMap<>();
    private Map<String, BaseFragment> mBaseFragmentByName = new HashMap<>();
    private Map<Integer, String> mFragmentNameByDrawerId = new HashMap<>();


    private Fragment getFragment(int position) {
        Fragment f = mFragmentMap.get(position);
        if (f == null) {
            if (position == 0) {//如果是最近头条，特殊处理
                f = new HeadlineLatestListFragment();
            } else {
                int comid = mPagerAdapter.getColumns().get(position).getId();
                f = HeadlineColumnListFragment.newInstance(comid);
            }
            mFragmentMap.put(position, f);
        }
        return f;

    }

    public static Fragment newInstance() {
        return new HeadlineMainFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }


    @Override
    protected void initViews() {
        super.initViews();
        //FIXME mToolbar为什么有时候会为空呢？IDE的问题？
        if (mToolbar != null) {
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //FIXME 改成eventbus传输
                    ((MainActivity) getActivity()).toggleMenu();
                }
            });
        }
        mLoadingView.setVisibility(View.GONE);
//        if(mPagerAdapter == null){
        presenter.getHeadlineColumns();
//        }else{
//
//            mViewPager.setAdapter(mPagerAdapter);
//           // mViewPager.setOffscreenPageLimit(columns.size());
//            mTabLayout.setupWithViewPager(mViewPager);
//        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public String getToolbarTitle() {
        return "头条";
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_headline_main;
    }

    public void showLoading() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    public void showError(String msg) {
        mLoadingView.setVisibility(View.GONE);
        TipUtil.showSnack(getActivity(), msg);
    }

    public void showHeadlineColumns(List<HeadlineColumnBean> columns) {
        //TODO 引导视图：告诉别人可以点击头部返回顶部
        mLoadingView.setVisibility(View.GONE);
        mPagerAdapter = new HeadlinePagerAdapter(getChildFragmentManager(), columns);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(columns.size());
        mTabLayout.setupWithViewPager(mViewPager);
        //google这样设置不太合适，会覆盖掉自己的回调
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition());
                Logger.i("onTabSelected--%s ", tab.getText());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Logger.i("onTabUnselected--%s ", tab.getText());
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Logger.i("onTabReselected--%s ", tab.getText());
                //最新头条 将id设为0
                int commid = tab.getPosition() == 0 ? 0 : mPagerAdapter.getColumns().get(tab.getPosition()).getId();
                AppService.getInstance().getBus().post(new HeadlineTabReselectedEvent(commid));
            }
        });
    }

    @NonNull
    @Override
    public HeadlineMainPresenter createPresenter() {
        return new HeadlineMainPresenter();
    }

    class HeadlinePagerAdapter extends FragmentPagerAdapter {

        List<HeadlineColumnBean> columns;

        public List<HeadlineColumnBean> getColumns() {
            return columns;
        }

        public HeadlinePagerAdapter(FragmentManager fm, List<HeadlineColumnBean> columns) {
            super(fm);
            this.columns = columns;
        }

        @Override
        public Fragment getItem(int position) {
            return getFragment(position);
        }

        @Override
        public int getCount() {
            return columns.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return columns.get(position).getName();
        }
    }

}
